<?php

namespace app\api\server;

use app\common\model\user\Address as UserAddress;

/**
 * 收货地址逻辑
 */
class Address
{


    /**
     * 设置用户默认地址
     * @param int  $uid
     * @return array
     */
    public static function setDefaultAddress($id, $uid)
    {
        UserAddress::where('user_id', $uid)->update(['is_default' => 0]);
        return UserAddress::where('user_id', $uid)->where('id', $id)->update(['is_default' => 1]);
    }

    /**
     * 获取默认地址
     * @param int  $uid
     * @return array
     */
    public static function getDefaultAddress($uid)
    {
        return UserAddress::where('is_default', 1)->where('user_id', $uid)->find();
    }
    /**
     * 获取用户收货地址
     * @param int  $uid
     * @return array
     */
    public static function getUserAddress($uid)
    {
        return UserAddress::where('user_id', $uid)->paginate(10);
    }

    /**
     * 用户添加收货地址
     * @param int  $uid
     * @return array
     */
    public static function AddAddress($data)
    {
        if ($data['is_default'] == 1) {
            UserAddress::where('user_id', $data['user_id'])->update(['is_default' => 0]);
        }
        $model = new UserAddress();
        if (isset($data['id'])) {
            $model->get($data['id']);
            return $model->isUpdate(true)->save($data);
        }
        return $model->allowField(true)->save($data);
    }

    /**
     * 删除收货地址
     * @param int  $uid
     * @return array
     */
    public static function delAddress($id, $uid)
    {

        return UserAddress::where('id', $id)->where('user_id', $uid)->delete();
    }
}
